from datetime import datetime

from flask import Blueprint, render_template, request, jsonify, session
from flask_login import login_required
from werkzeug.security import generate_password_hash

from applications.common import curd
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id, enable_is_on_sale, \
    disable_is_on_sale, enable, disable
from applications.common.helper import ModelFilter
from applications.common.utils.getopenid import get_openid, token
from applications.common.utils.http import table_api, success_api, fail_api, wxuser_success_api, goods_api, carts_api, \
    bandas_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.exts import db
from applications.exts.cache import cache
from applications.models import Role, Power, User, Goods, Classify, Carts
from applications.models.bands import Bands
from applications.models.wx_user import WxUser
from applications.schemas import RoleOutSchema, PowerOutSchema2, WxUserOutSchema, GoodsOutSchema, WxUClassifyOutSchema, \
    CartsOutSchema, BandasOutSchema
from applications.common.utils import upload as upload_curd

bandas = Blueprint('bandas', __name__, url_prefix='/bandas')


# 管理
@bandas.route('/')
@login_required
# flask 实现 Authorization请求报头认证
# @authorize("wxuser:role:main", log=True)
def main():
    return render_template('bandas/main.html')


#   分页查询
@bandas.route('/data')
@login_required
# @authorize("admin:user:main", log=True)
def data():
    # 获取请求参数
    name = xss_escape(request.args.get('name', type=str))
    # 查询参数构造
    mf = ModelFilter()
    if name:
        mf.contains(field_name="name", value=name)
    # if dept_id:
    #     mf.exact(field_name="dept_id", value=dept_id)
    # orm查询

    # 使用分页获取data需要.items
    banda = Bands.query.filter(mf.get_filter(model=Bands)).layui_paginate()
    count = banda.total
    # 返回api
    return table_api(data=model_to_dicts(schema=BandasOutSchema, data=banda.items), count=count)


# 增加
@bandas.route('/add')
@login_required
# @authorize("admin:user:add", log=True)
def add():
    classify = Classify.query.all()
    return render_template('bandas/add.html', classify=classify)


@bandas.route('/upload', methods=["POST"])
@login_required
def upphoto():
    file = 'file'
    if file in request.files:
        photo = request.files[file]
        mime = request.files[file].content_type
        # print(photo)

        file_url = upload_curd.upfile(file=photo, flag=0)

        print(file_url)
        file_url = request.host_url + file_url
        print('file_url:', file_url)
        res = {
            "msg": "上传成功",
            "code": 0,
            "success": True,
            "data":
                {"src": file_url}
        }
        return jsonify(res)
    return fail_api()


# 后台add
@bandas.route('/addbandas', methods=["POST"])
@login_required
# @authorize("admin:user:add", log=True)
def addbandas():
    req_json = request.json

    print('req_json:', req_json)

    name = xss_escape(req_json.get('name'))
    status = xss_escape(req_json.get('status'))
    photo = xss_escape(req_json.get('file'))

    if status == 'on':
        status = 1
    else:
        status = 0

    bandas = Bands()
    bandas.name = name
    bandas.enable = status
    bandas.photo = photo

    db.session.add(bandas)
    db.session.commit()
    return success_api(msg='添加成功')
    # code = xss_escape(req_json.get('code'))
    # userInfo = xss_escape(req_json.get('userInfo'))
    # print(code,userInfo)

    # code = req_json.get('code')
    # userInfo = req_json.get('userInfo')
    # username = userInfo.get('nickName')
    # avatarUrl = userInfo.get('avatarUrl')
    # openid = get_openid(code)
    # print(code, username, avatarUrl, openid)
    # wxtokens = token(code)
    # a = req_json.get("roleIds")
    # username = xss_escape(req_json.get('username'))
    # password = xss_escape(req_json.get('password'))
    # phone = xss_escape(req_json.get('phone'))
    # file = xss_escape(req_json.get('file'))
    #
    # wxuser = WxUser()
    # wxuser.username = username
    # wxuser.phone = phone
    # wxuser.set_password(password)
    # wxuser.avatar = file
    # db.session.add(wxuser)
    # db.session.commit()
    # # role_ids = a.split(',')
    #
    # if not username or not real_name or not password:
    #     return fail_api(msg="账号姓名密码不得为空")
    # #
    # if bool(User.query.filter_by(username=username).count()):
    #     return fail_api(msg="用户已经存在")
    # wxuser = WxUser(username=username, openid=openid, avatar=avatarUrl, enable=1)
    # user.set_password(password)
    # db.session.add(wxuser)
    # db.session.commit()
    # roles = Role.query.filter(Role.id.in_(role_ids)).all()
    # for r in roles:
    #     user.role.append(r)

    # wxuser_success_api(errno: int = 0, user:dict = {}, token:str = '', msg:str = ''):


# 展示
@login_required
@bandas.route('/enable', methods=["PUT"])
# @authorize("admin:user:edit", log=True)
def enables():
    _id = request.json.get('id')
    if _id:
        res = enable(model=Bands, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="上架成功")
    return fail_api(msg="数据错误")


# 不展示
@login_required
@bandas.route('/disable', methods=["PUT"])
# @authorize("admin:user:edit", log=True)
def dis_enable():
    _id = request.json.get('id')
    if _id:
        res = disable(model=Bands, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="下架成功")
    return fail_api(msg="数据错误")


# 删除
@bandas.route('/remove/<int:id>', methods=["DELETE"])
@login_required
# @authorize("admin:user:remove", log=True)
def delete(id):
    # user = User.query.filter_by(id=id).first()
    # user.role = []

    # res = User.query.filter_by(id=id).delete()

    res = Bands.query.filter_by(id=id).delete()

    db.session.commit()
    print('res:', res)
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


# 批量删除
@bandas.route('/batchRemove', methods=["DELETE"])
@login_required
# @authorize("admin:user:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        # wxuser = WxUser.query.filter_by(id=id).first()
        # user.role = []

        res = Bands.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")


# =======wx=====

@bandas.route('/bandaslist', methods=["GET"])
# @authorize("admin:user:remove", log=True)
def bandaslist():
    banda = Bands.query.all()
    bander = model_to_dicts(BandasOutSchema, data=banda)
    print(bander)
    return bandas_api(banner=bander, msg="查询成功")
